vertFont = 
"""
precision highp float;
attribute vec2 vertex; 


uniform mat3 spriteTransform; 
uniform vec4 screen;
uniform vec2 frame;
uniform vec2 spriteSheetSize;

varying highp vec2 coord;

void main() { 
  vec3 homogeniousCoord = vec3(vertex, 1.0);
  gl_Position = vec4(homogeniousCoord * spriteTransform, 1.0) * screen; 
  coord = (vertex + frame) / spriteSheetSize;
}
"""

fragFont = 
"""
precision highp float;
varying highp vec2 coord;
uniform sampler2D spriteTexture;
uniform vec4 color;
 
void main() { 
  gl_FragColor = texture2D(spriteTexture, coord) * color; 
}
"""

class window.SpriteRender
  constructor : (ctx) ->
    @buff = ctx.MeshBuffer(8)
    @buff.addDescription "vertex", "FLOAT", 2
    identity = new window.Transform2D()
    @prog = ctx.Program()
    @prog.setFragSource fragFont
    @prog.setVertSource vertFont
    @prog.link()
    @prog.use()
    @worldTransform = new window.Transform2D()
    @prog.u4f "color", 1.0, 1.0, 1.0, 1.0

    #@prog.um3f "worldTransform", identity.getMatrix()
    @prog.um3f "spriteTransform", identity.getMatrix()
    @texture = null

  setSpriteSheet : (@texture, @w, @h) ->
    @prog.use()

    @buff.clear()
    @buff.pushff 0.0, 0.0
    @buff.pushff @w, 0.0
    @buff.pushff @w, @h
    @buff.pushff 0.0, @h
    @buff.pushiii 0, 1, 2
    @buff.pushiii 2, 3, 0
    @buff.upload()
    
    

  use : () -> 
    @prog.use()
    @buff.setup @prog
    @prog.u2f "spriteSheetSize", @texture.width, @texture.height
    @prog.attachTexture "spriteTexture", 0, @texture

  setColor : (r, g, b, a) ->
    @prog.u4f "color", r, g, b, a

  setWorldTransform : (worldTransform) -> 
    @worldTransform = worldTransform
    #@prog.um3f "worldTransform", worldTransform.getMatrix()

  drawSprite : (frame, spriteTransform) -> 
    return false if @texture == null
    return false if @texture.ready == false


    spriteTransform.translate @worldTransform.t[2], @worldTransform.t[5]

    @prog.u2f "frame", frame[0], frame[1]
    @prog.um3f "spriteTransform", spriteTransform.getMatrix()

    @buff.draw()

    true




